import request from '@/utils/request'
import Cookies from 'js-cookie'

const state = {
  token: Cookies.get('token') || '',
  userInfo: JSON.parse(Cookies.get('userInfo') || '{}'),
  userRole: Cookies.get('userRole') || '',
  permissions: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    console.log('SET_TOKEN mutation:', token)
    state.token = token
    Cookies.set('token', token)
  },
  SET_USER_INFO: (state, userInfo) => {
    console.log('SET_USER_INFO mutation:', userInfo)
    state.userInfo = userInfo
    Cookies.set('userInfo', JSON.stringify(userInfo))
  },
  SET_USER_ROLE: (state, role) => {
    console.log('SET_USER_ROLE mutation:', role)
    state.userRole = role
    Cookies.set('userRole', role)
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  CLEAR_USER_DATA: (state) => {
    state.token = ''
    state.userInfo = {}
    state.userRole = ''
    state.permissions = []
    Cookies.remove('token')
    Cookies.remove('userInfo')
    Cookies.remove('userRole')
  }
}

const actions = {
  // 管理员登录
  adminLogin({ commit }, userInfo) {
    const { adminCode, password } = userInfo
    return new Promise((resolve, reject) => {
      request.post('/auth/admin/login', {
        adminCode: adminCode.trim(),
        password: password
      }).then(response => {
        console.log('adminLogin response:', response)
        
        // response拦截器已经处理过了，直接使用response
        const responseData = response
        
        console.log('responseData:', responseData)
        
        if (responseData.code === 200) {
          const loginData = responseData.data
          console.log('loginData:', loginData)
          
          // 检查 loginData 的结构
          if (!loginData) {
            console.error('loginData is null or undefined')
            reject(new Error('登录数据为空'))
            return
          }
          
          const token = loginData.token
          const userInfo = loginData.userInfo
          const role = loginData.role
          
          console.log('extracted data:', { token, userInfo, role })
          
          // 检查必要的字段是否存在
          if (!token) {
            console.error('token is missing')
            reject(new Error('缺少认证令牌'))
            return
          }
          
          if (!role) {
            console.error('role is missing')
            reject(new Error('缺少用户角色'))
            return
          }
          
          commit('SET_TOKEN', token)
          commit('SET_USER_INFO', userInfo || {})
          commit('SET_USER_ROLE', role)
          
          resolve(responseData)
        } else {
          reject(responseData)
        }
      }).catch(error => {
        console.error('adminLogin error:', error)
        reject(error)
      })
    })
  },

  // 网格员登录
  gridMemberLogin({ commit }, userInfo) {
    const { gmCode, password } = userInfo
    return new Promise((resolve, reject) => {
      request.post('/auth/grid/login', {
        gmCode: gmCode.trim(),
        password: password
      }).then(response => {
        const responseData = response
        if (responseData.code === 200) {
          const loginData = responseData.data
          const { token, userInfo, role } = loginData
          commit('SET_TOKEN', token)
          commit('SET_USER_INFO', userInfo || {})
          commit('SET_USER_ROLE', role)
          
          resolve(responseData)
        } else {
          reject(responseData)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 公众监督员登录
  supervisorLogin({ commit }, userInfo) {
    const { supervisorCode, password } = userInfo
    return new Promise((resolve, reject) => {
      request.post('/auth/supervisor/login', {
        supervisorCode: supervisorCode.trim(),
        password: password
      }).then(response => {
        const responseData = response
        if (responseData.code === 200) {
          const loginData = responseData.data
          const { token, userInfo, role } = loginData
          commit('SET_TOKEN', token)
          commit('SET_USER_INFO', userInfo || {})
          commit('SET_USER_ROLE', role)
          
          resolve(responseData)
        } else {
          reject(responseData)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 公众监督员注册
  supervisorRegister({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      request.post('/auth/supervisor/register', userInfo).then(response => {
        const { data } = response
        if (data.code === 200) {
          resolve(data)
        } else {
          reject(data)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (!state.token) {
        reject('No token')
        return
      }
      
      request.get('/auth/userinfo').then(response => {
        const { data } = response
        if (data.code === 200) {
          const { userInfo, role } = data.data
          commit('SET_USER_INFO', userInfo)
          commit('SET_USER_ROLE', role)
          resolve(data)
        } else {
          reject(data)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 验证token
  validateToken({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (!state.token) {
        resolve(false)
        return
      }
      
      request.get('/auth/userinfo').then(response => {
        const { data } = response
        if (data.code === 200) {
          const { userInfo, role } = data.data
          commit('SET_USER_INFO', userInfo)
          commit('SET_USER_ROLE', role)
          resolve(true)
        } else {
          commit('CLEAR_USER_DATA')
          resolve(false)
        }
      }).catch(error => {
        commit('CLEAR_USER_DATA')
        resolve(false)
      })
    })
  },

  // 退出登录
  logout({ commit }) {
    return new Promise((resolve) => {
      commit('CLEAR_USER_DATA')
      resolve()
    })
  }
}

const getters = {
  token: state => state.token,
  userInfo: state => state.userInfo,
  userRole: state => state.userRole,
  permissions: state => state.permissions,
  isLoggedIn: state => !!state.token,
  isAdmin: state => state.userRole === 'ADMIN',
  isGridMember: state => state.userRole === 'GRID_MEMBER',
  isSupervisor: state => state.userRole === 'SUPERVISOR'
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 